﻿using System;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

namespace Red.Scripts.Options.Tool.Pane
{
    public static class Utilities
    {
        public static bool Open< T >()
        {
            Guid guid = typeof( T ).GUID;

            return Open( guid );
        }

        public static bool Open( Guid guid )
        {
            IVsWindowFrame window = FindOrCreate( guid );

            if( window != null )
            {
                window.Show();

                return true;
            }

            return false;
        }

        private static IVsWindowFrame FindOrCreate( Guid guid )
        {
            IVsUIShell shell = (IVsUIShell)ServiceProvider.GlobalProvider.GetService( typeof( SVsUIShell ) );

            IVsWindowFrame windowFrame;
            if ( shell.FindToolWindow( (uint)__VSFINDTOOLWIN.FTW_fFindFirst, ref guid, out windowFrame ) == VSConstants.S_OK )
                return windowFrame;

            if ( shell.FindToolWindow( (uint)__VSFINDTOOLWIN.FTW_fForceCreate, ref guid, out windowFrame ) == VSConstants.S_OK )
                return windowFrame;

            return null;
        }
    }
}
